package br.com.javamagazine;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.javamagazine.jdo.UserFoto;
import br.com.javamagazine.jdo.UserFotoDAO;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class WelcomeServlet extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException
  {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    if (user != null) {
      req.setAttribute("user", user);
      req.setAttribute("logouturl", userService.createLogoutURL("/"));
      
      UserFoto userFoto = (UserFoto) UserFotoDAO
          .getUserFoto(user.getNickname());
      if (userFoto != null) {
        req.setAttribute("updateTime", SimpleDateFormat.getDateTimeInstance()
            .format(userFoto.getUpdateTime()));
      }      
      req.getRequestDispatcher("/fotouser.jsp").forward(req, resp);
    }
    else {
      req.setAttribute("loginurl", userService.createLoginURL("/"));
      req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
    }
  }
}
